<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $guarded = [];

    protected $dateFormat = 'U';

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public static function _after_insert($data)
    {
        //
    }

    public static function _after_update($data)
    {
        //
    }

    public static function _after_delete($data)
    {
        //
    }

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {
        foreach ($list as &$item) {
            $item = self::formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        if ($item['avatar']) {
            $item['full_avatar'] = full_file_url($item['avatar']);
        } else {
            $item['full_avatar'] = letter_avatar($item['nickname']);
        }

        if (isset($params['format_source']) && $params['format_source'] == 'backend') {
            // 角色
            if ($item['type'] == 0) {
                $item['role_names'] = '超级管理员';
            } else {
                $roleIds = AdminRoleUser::where('admin_id', $item['id'])->pluck('role_id')->toArray();
                $roleNames = AdminRole::whereIn('id', $roleIds)->pluck('name')->toArray();
                $item['role_ids'] = $roleIds;
                $item['role_names'] = $roleNames ? implode('、', $roleNames) : '';
            }
        } else {
            //
        }

        return $item;
    }

    /**
     * 删除
     */
    public static function doDelete($id)
    {
        AdminRoleUser::where('admin_id', $id)->delete();

        return self::where('id', $id)->delete();
    }

    /**
     * 是否被使用过
     */
    public function isUsed($id, $param = '')
    {
        if (!$id) {
            return ['code' => 0, 'msg' => '参数错误'];
        }

        // 软删除
        return ['code' => 2, 'msg' => ''];
    }
}
